import React from 'react';

import { allCity, province } from './data';

export interface CityValue {
  province?: string;
  city?: string;
}

export interface CitySelectProps {
  value?: CityValue;
  onChange?: (value: CityValue) => void;
  placeholder?: {
    province?: string;
    city?: string;
  };
  disabled?: boolean;
  allowClear?: boolean;
}

const CitySelect: React.FC<CitySelectProps> = ({
  value,
  onChange,
  placeholder = { province: '请选择省份', city: '请选择城市' },
  disabled = false,
  allowClear = true,
}) => {
  // 根据选中的省份过滤城市
  const getCityOptions = (): Array<{ label: string; value: string }> => {
    if (!value?.province) {
      return [];
    }
    return allCity
      .filter(city => city.prov === value.province)
      .map(city => ({
        label: city.label,
        value: city.label, // 使用 label 作为 value
      }));
  };

  const handleProvinceChange = (provinceCode: string) => {
    const newValue: CityValue = {
      province: provinceCode,
      city: undefined, // 省份改变时清空城市
    };
    onChange?.(newValue);
  };

  const handleCityChange = (cityCode: string) => {
    const newValue: CityValue = {
      ...value,
      city: cityCode,
    };
    onChange?.(newValue);
  };

  return (
    <ARow gutter={8}>
      <ACol span={12}>
        <ASelect
          value={value?.province}
          options={province}
          placeholder={placeholder.province}
          disabled={disabled}
          allowClear={allowClear}
          onChange={handleProvinceChange}
        />
      </ACol>
      <ACol span={12}>
        <ASelect
          value={value?.city}
          options={getCityOptions()}
          placeholder={placeholder.city}
          disabled={disabled || !value?.province}
          allowClear={allowClear}
          onChange={handleCityChange}
        />
      </ACol>
    </ARow>
  );
};

export default CitySelect;
